<?php
class IndexAction extends CommonAction{
    public function index(){
		$team = new CreatTeamModel();
		$this->assign('info',$team->info);
		$this->assign('iscreatteam',$team->iscreatteam);//团队信息显示;
		$this->assign('newteam',$team->newteam);//团队信息显示;
		$this->assign('hotteam',$team->hotteam);//热门评论团队;
		$this->assign('mostvoteteam',$team->mostvoteteam);//投票最多团队;
		$this->assign('mostteacher',$team->mostteacher);//最新评论老师/教官;
		$this->assign('Identity',$team->Identity);		//识别访客身份  1.队长进入自己的主页 2.队员进入自己的主页 3.队长进入别人的团队页 4。队员进入别人的团队页 5.游客
		//最新参赛历程
		import('ORG.Util.Page');
		$count = M()->query("select count(*) num from teamblogs tb,team t,bloglog b,users u where tb.IsApproved=1 and  b.IsDeleted=0 and tb.TeamId=t.Id and tb.BlogId=b.Id and b.CreateUser=u.UserId");
		$page = new Page($count[0]['num'],20);
		$show = $page->show();
		$this->assign('page',$show);
		$list = M()->limit($page->firstRow.','.$page->listRows)->query("select b.Id,b.Title,b.Content,b.ViewCount,b.TrueName,b.CreateUser,b.CommentCount,b.CreateDate,t.Id tid,t.Name tname,t.Captain,t.CaptainName,u.OrgName from teamblogs tb,team t,bloglog b,users u where tb.IsApproved=1 and  b.IsDeleted=0 and tb.TeamId=t.Id and tb.BlogId=b.Id and b.CreateUser=u.UserId");
		$this->assign('list',$list);
		$this->display();
    }
	//登录成功，创建或参加团队
	public function run(){
		$this->display();
	}
	//搜索参赛队
	public function searchTeam(){
		$team = new CreatTeamModel();
		$this->assign('info',$team->info);
		$this->assign('iscreatteam',$team->iscreatteam);//团队信息显示;
		$this->assign('newteam',$team->newteam);//团队信息显示;
		$this->assign('hotteam',$team->hotteam);//热门评论团队;
		$this->assign('mostvoteteam',$team->mostvoteteam);//投票最多团队;
		$this->assign('mostteacher',$team->mostteacher);//最新评论老师/教官;
		$this->assign('Identity',$team->Identity);		//识别访客身份  1.队长进入自己的主页 2.队员进入自己的主页 3.队长进入别人的团队页 4。队员进入别人的团队页 5.游客
		$Data = M('Team'); // 实例化Data数据对象
    	import('ORG.Util.Page');// 导入分页类
    	$where = '';
    	//if(!empty($_POST['TeamName'])){
    	$map['Name'] =array('like',array('%'.$_POST['TeamName'].'%'));
		//}
    	//if(!empty($_POST['School'])){
    	$map['SchoolName'] =array('like',array('%'.$_POST['School'].'%'));
    	//}
    	if($_POST['MatchStatus'] != 0){
    	$map['Status'] = array('eq',$_POST['MatchStatus']);
    	}
    	$count = $Data->where($map)->count();// 查询满足要求的总记录数 $map表示查询条件;
    	$Page = new Page($count,4);// 实例化分页类 传入总记录数
    	$show = $Page->show();// 分页显示输出
    	//print_r($vo);
    	$list = $Data->where($map)->order('CraeteDate')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('list',$list);// 赋值数据集
    	$this->assign('page',$show);// 赋值分页输出
    	$this->display(); // 输出模板
	}
	//最新团队
	public function bar_newTeam(){
		$team = new CreatTeamModel();
		$this->assign('newteam',$team->newteam);//团队信息显示;
		$this->display();
	}
	
	//向团队管理员发送申请人请求
	public function applyTeam(){
		if($_SESSION[C('USER_AUTH_KEY')]['UserType']==2){
				$id = $this->_get("id");
				$apply = M('Teammembers');
				$data['TeamId'] = $id;
				$data['UserId'] = $_SESSION[C('USER_AUTH_KEY')]['UserId'];
				$data['TrueName'] = $_SESSION[C('USER_AUTH_KEY')]['TrueName'];
				$data['Info'] = $this->_post('JoinInfo');
				$data['IsApproved'] = 0;
				$data['CreateDate'] = date("Y-m-d H:i:s");
				$teamname = $apply->add($data);
				if($teamname){
					
					 echo '<script>window.parent.callbackfun(true,null);</script>';
				}else{
					 echo '<script>window.parent.callbackfun(false,null);</script>';
					
				}
		}else{
				echo "<script>alert('您不能加入团队');</script>";
			}
			
			
	}
	//接收加入参赛队申请 
	public function joinTeam(){
		if($this->_get("id") != $this->getmyteamid()){
			if($_SESSION[C('USER_AUTH_KEY')]['UserType']==2 ){
				$id = $this->_get("id");
				$apply = M('Teammembers');
				$count = $apply->where('IsApproved=1 AND TeamId = '.$id )->count(); 
				if($count<5){
					$isagree=1;
					$Data = M('Team');
					$list = $Data->where('Id ='.$id)->find();
					$this->assign('list',$list);
					$this->assign("isagree",$isagree);
					
					$res=M()->query('select Id from teammembers where IsApproved=0 and TeamId='.$id.' and UserId='.$_SESSION[C('USER_AUTH_KEY')]['UserId']);
					// dump($res);
					if($res){
						echo '<script>closewindoe(true,true)</script>';
						return false;
					}else{
						$this->display(); // 输出模板			
					}
				}else{
					$isagree=0;
					echo '<script>closewindoe(true,null)</script>';
				}
			}else{
				echo "<script>alert('您不能加入团队');</script>";
			}
		}else{
				echo "<script>alert('不用加入自己的团队了');</script>";
		}
	}
	
	
	//加为友情团队
	public function addFriendTeam(){
		if($_SESSION[C('USER_AUTH_KEY')]['UserType']==2){
			$id = $this->_post('id');	//被我邀请的团队的ID
			$myteamid=$this->getmyteamid();	//我的团队的ID

			$sql1='select Id from friendlyteam where TeamId1='.$myteamid.' and TeamId2='.$id.' and IsApproved=1'; 	//查看是否已经是批准的好友团队
			$sql2='select Id from friendlyteam where TeamId1='.$myteamid.' and TeamId2='.$id.' and IsApproved=0';	//查看是否已经发送过请求
			$sql3='select Id from friendlyteam where TeamId1='.$myteamid.' and IsApproved=0';						//查看我所有的发送的没有通过的请求的个数

			if($res1 = M()->query($sql1)){
				die('你们已经是友情团队了，请勿再次发送请求。');
			}
			if(count($res3 = M()->query($sql3))>=8){
				die('您选择加入的友情团队超过规定数量,就不要再点击了。');
			}
			if($res2 = M()->query($sql2)){
				die('您已经发送过请求了，请勿再次发送请求(⊙o⊙)哦。');
			}
			$add = M()->execute('insert into friendlyteam(Id,TeamId1,TeamId2,IsApproved,Version) values ( NULL,'.$this->getmyteamid().','.$id.',"0","0")');
			if($add){
				echo '已经发出请求，请等待队长审核';
			}else{
				echo '发送请求失败';
			}
		}else{
			echo "<script>alert('您不能加入团队');</script>";
		}
	}
	public function getmyteamid(){
		$myid=$_SESSION[C('USER_AUTH_KEY')]['UserId'];
		$teaminfo=M()->query('select Id from team where Captain='.$myid);
		return $teaminfo[0]['Id'];
	}
	
	
	//更多参赛队
	public function teamMore(){
		$res = M()->query('
						SELECT Id,Name,Logo
						FROM team
						ORDER BY CraeteDate DESC
						LIMIT 12
					');
		$this->assign('res',$res);
		$this->display();
	}
	//弹出
	public function can(){
		if($_SESSION[C('USER_AUTH_KEY')]['UserType']==2){
			$db = M('Team');
			$res = $db->where("Captain=".$_SESSION[C('USER_AUTH_KEY')]['UserId'])->find();
			//判断是否已建立团队，只能建立一个团队
			if(!empty($res)){
				$this->assign('iscreate',1);
			}else{
				$this->assign('iscreate',-1);
			}
				$this->display();
			}else{
				echo "<script>alert('您不能加入团队');</script>";
			}
			
		}
	//创建参赛队信息表单
	public function teamForm(){
		//$_SESSION[C('USER_AUTH_KEY')]['Id']=4;//debug 模拟session
		$user=M('Users')->where("UserId=".$_SESSION[C('USER_AUTH_KEY')]['UserId'])->find();
		$this->assign('user',$user);
		$this->display();
	}
	//检测团队名称是否已有
	public function teamName(){
		$db = M('Team');
		$res = $db->where("Name='".$_GET['txtTeamName']."'")->find();
		if(empty($res)){
			$this->ajaxReturn($_GET['txtTeamName'],'OK',1);
		}else{
			$this->ajaxReturn($_GET['txtTeamName'],'ERROR',-1);
		}
	}
	//创建参赛团队
	public function createTeam(){
		if($_SESSION[C('USER_AUTH_KEY')]['UserType']==2){
			//2次过滤
			$db = M('Team');
			//$_SESSION[C('USER_AUTH_KEY')]['Id']=6;//debug 模拟session
			$res = $db->where("Captain=".$_SESSION[C('USER_AUTH_KEY')]['UserId'])->find();
			//判断是否已建立团队，只能建立一个团队
			if(!empty($res)){
				$this->error('你已创建团队，你只能创建一个团队');
				exit;
			}
			//判断名字是否重复
			$res = $db->where("Name='".$_POST['Name']."'")->find();
			if(!empty($res)){
				$this->error('团队名称重复，请换一个！');
				exit;
			}
			//正则匹配2次过滤
			if(!preg_match("/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]{1,16}$/u",$_POST['Name'])){
				$this->error('团队名称格式不对，请重新填写！');
				exit;
			}
			if(!preg_match("/^[1-9]{1}[0-9]{8}$/",$_POST['Fetion'])){
				$this->error('飞信格式不对，请重新填写！');
				exit;
			}
			//判断是否选择了上传头像
			if(empty($_FILES['Logo']['name'])){
				$_POST['Logo'] = 'default.gif';
			}else{
				import('ORG.Net.UploadFile');
				$upload = new UploadFile();// 实例化上传类
				$upload->maxSize  = 1024000 ;// 设置附件上传大小1M
				$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
				$upload->savePath =  './UpFile/Img/TeamFace/';// 设置附件上传目录
				//设置需要生成缩略图，仅对图像文件有效
				$upload->thumb = true;
				// 设置引用图片类库包路径
				$upload->imageClassPath = 'ORG.Util.Image';
				//设置需要生成缩略图的文件后缀
				$upload->thumbPrefix = 'logo_';  //产生1张缩略图
				//设置缩略图最大宽度
				$upload->thumbMaxWidth = '120';
				//设置缩略图最大高度
				$upload->thumbMaxHeight = '120';
				//设置上传文件规则
				$upload->saveRule = uniqid;
				//删除原图
				$upload->thumbRemoveOrigin = true;
				if(!$upload->upload()){
					// 上传错误提示错误信息
					$this->error($upload->getErrorMsg());
				}else{
					// 上传成功 获取上传文件信息
					$info =  $upload->getUploadFileInfo();
					$_POST['Logo'] = 'logo_'.$info[0]['savename'];
				}
			}
			//拼装数据
			$user=M('Users')->where("UserId=".$_SESSION[C('USER_AUTH_KEY')]['UserId'])->find();
			$_POST['CraeteDate'] = date('Y-m-d H:i:s');
			$_POST['Status'] = 1;
			$_POST['Poll'] = 0;
			$_POST['Score'] = 0;
			$_POST['SchoolId'] = $user['SchoolId'];
			$_POST['SchoolName'] = $user['OrgName'];
			$_POST['Captain'] = $user['UserId'];//用户UserId作为Team的Captain
			$_POST['CaptainName'] = $user['TrueName'];
			$_POST['ProblemId'] = '';
			$_POST['Division'] = '';
			$_POST['Version'] = '1.0';
			$teamid = $db->add($_POST);
			//$db->create();
			//teammembers表
			$data['TeamId'] = $teamid;
			$data['UserId'] = $user['UserId'];
			$data['IsApproved'] = 1;
			$data['TrueName'] = $user['TrueName'];
			$data['Info'] = '队长';
			$data['Version'] = '1.0';
			$data['CreateDate'] = date('Y-m-d H:i:s');
			if( $teamid && M('Teammembers')->add($data)){
				//跳到个人主页
				$this->redirect('Student/Home/index',array('id'=>$user['UserId']));
			}else{
				//失败返回
				$this->error('创建失败');
			}
		}else{
			echo "<script>alert('您不能加入团队');</script>";
		}
    }
	
}
